# blib/plugs/mail.py
#
#

""" mail analyser. """

## blib imports

from blib import O, cmnds

## generic imports

import email.header
import logging
import email
import time
import os

## Email class

class Email(O):

    def from_file(self, fn):
        f = open(fn, "r")
        self.email = email.message_from_file(f)

    def get(self, item):
        header = email.header(self.text)
        return header.get(item)

    def search(self, search=None):
        result = []
        for line in self.email:
            if search in line: result.append(line)
        return result

## Emails class

class Emails(O):

    def from_dir(self, ddir):
        for fn in os.listdir(ddir):
            time.sleep(0.001)
            filename = os.path.join(ddir, fn)
            logging.warn("reading %s" % filename)
            try: self.add(Email().from_file(filename))
            except Exception as ex: 
                if os.path.isdir(filename): self.from_dir(filename) ; continue
                else: logging.warn("error occured: %s" % str(ex))

    def add(self, email):
        if not self.emails: self.emails = []
        self.emails.append(email)

    def group(self, item, search=None):
        for email in self.emails:
            if search and search not in email.get(item) : continue
            yield email

    def save(self):
        for email in self.emails: email.save()

## emails variable

emails = Emails()

## from_dir command

def from_dir(event):
    if not event.rest: event.reply("i require a directory to work on.") ; return
    global emails
    emails.from_dir(event.rest)
    if emails.emails: event.reply("read %s emails" % len(emails.emails))
    emails.save()

cmnds.register("from_dir", from_dir)
